import { useUserStore } from '@store';
import type { Router } from 'vue-router';
import 'nprogress/nprogress.css'; // progress bar style
import NProgress from 'nprogress'; // progress bar

export const setupGuard = (router: Router) => {
  progress(router);
  routerGuard(router);
};

const progress = (router: Router) => {
  router.beforeEach(() => {
    NProgress.start();
  });

  router.afterEach(() => {
    NProgress.done();
  });
};

const routerGuard = (router: Router) => {
  const whiteList = ['/login'];
  // 路由守卫
  router.beforeEach(async (to, _from, next) => {
    const { userState, initUserInfo } = useUserStore();
    // 判断是否已经登录
    if (userState.loginInfo.status) {
      try {
        if (userState.menus.length === 0) {
          await initUserInfo();
        }
        next();
      } catch (error) {
        // MessagePlugin.error(error.message);
        next({
          path: '/login',
          query: { redirect: encodeURIComponent(to.fullPath) },
        });
      }
    } else {
      if (whiteList.includes(to.path)) {
        next();
      } else {
        next({
          path: '/login',
          query: { redirect: encodeURIComponent(to.fullPath) },
        });
      }
    }
  });

  router.afterEach((to, _from) => {
    // 跳转登录，重置空登录信息
    if (to.path === '/login') {
      const { resetState } = useUserStore();
      resetState();
      // permissionStore.restoreRoutes();
    }
  });
};
